import pickle
import random
import re

from pypinyin import pinyin
from pypinyin import lazy_pinyin

# 获取字典
with open('./easy_poemDict.pk', 'rb') as f:#rb二进制读的方式
    esay_poem_dict = pickle.load(f)#打开字典文件
    f.close()

with open('./normal_poemDict.pk', 'rb') as f:#rb二进制读的方式
    normal_poem_dict = pickle.load(f)#打开字典文件
    f.close()

with open('./hard_poemDict.pk', 'rb') as f:#rb二进制读的方式
    hard_poem_dict = pickle.load(f)#打开字典文件
    f.close()

def jielong_easy( str ):
    newStr = re.sub(r'[。？！]', '', str)
    test = lazy_pinyin(newStr)  # 每个字的拼音
    tail = "".join(test[-1])
    print(tail)
    if tail not in esay_poem_dict.keys():  # 如果没有在字典中找到这个字
        return "false"
    else:
        return random.sample(esay_poem_dict[tail], 1)[0]

def jielong_normal( str ):
    newStr = re.sub(r'[。？！]','',str)
    # tail = newStr[-1]  # 最后一个字
    test = pinyin(newStr)  # 每个字的拼音
    tail = "".join(test[-1])
    print(tail)
    if tail not in normal_poem_dict.keys():  # 如果没有在字典中找到这个字
        return "false"
    else:
        return random.sample(normal_poem_dict[tail], 1)[0]

def jielong_hard( str ):
    newStr = re.sub(r'[。？！]','',str)
    tail = newStr[-1]  # 最后一个字
    # print(newStr)
    tail = "".join(tail)
    if tail not in hard_poem_dict.keys():  # 如果没有在字典中找到这个字
        return "false"
    else:
        return random.sample(hard_poem_dict[tail], 1)[0]

# print('\n请输入一句诗开始：')

while True:
    try:
        enter = str(input())
        while enter != 'exit':
            data = jielong_hard(enter)
            # print(data)
            if data != 'false':
                print("机器回复："+ '\n'+ data)
                print("您的回复：")
            else:
                print('被你打败啦，我没办法接这句诗。\n')
            break
    except Exception as err:
        print(err)
    # finally:#当出现所有错误时，则返回选择项（就是mode0或者是mode1）
    #   print('\n系统崩溃啦！ ')
